package pl.put.augrelshooter.activities;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import pl.put.augrelshooter.R;
import pl.put.augrelshooter.adapters.ServerListAdapter;
import pl.put.augrelshooter.connection.GameConnection;
import pl.put.augrelshooter.connection.NsdHelper;
import pl.put.augrelshooter.logic.game.badges.AllBadges;
import pl.put.augrelshooter.logic.game.badges.Badge;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.nsd.NsdServiceInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class JoinGameActivity extends Activity {
	NsdHelper nsdHelper;
	NsdServiceInfo selectedServer;
	ServerListAdapter serversAdapter;
	ListView serversListView;
	
	private GameConnection connection;
	private Handler updateHandler;
	
	private String gameName;
	private String badge;
	private String enemyColor;
	private String enemyName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join_game);

		nsdHelper = new NsdHelper(this);
		nsdHelper.initializeNsd(0);
		
		nsdHelper.discoverServices();

		List<NsdServiceInfo> serverList = new ArrayList<NsdServiceInfo>(
				nsdHelper.getDiscoveredServices().values());
		NsdServiceInfo[] servers = serverList.toArray(new NsdServiceInfo[serverList.size()]);
		serversAdapter = new ServerListAdapter(getBaseContext(), servers);
		
		serversListView = (ListView) findViewById(R.id.serverListView);
		serversListView.setAdapter(serversAdapter);
		
		serversListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
				selectedServer = (NsdServiceInfo) adapter.getItemAtPosition(position);
				((TextView)findViewById(R.id.playerNameLabelJoin)).setVisibility(View.VISIBLE);
				((EditText)findViewById(R.id.playerNameJoin)).setVisibility(View.VISIBLE);
			}
		});
	}
	
	@Override
	protected void onStop() {
		nsdHelper.tearDown();
		super.onStop();
	}

	@SuppressLint("HandlerLeak")
	public void joinGameButtonClicked(View v) {
		nsdHelper.resolveService(selectedServer);
		
		selectedServer = null;
		while (selectedServer == null) {
			selectedServer = nsdHelper.getChoosenService();			
		}
		
		updateHandler = new Handler() {
			@Override
			public void handleMessage(Message data) {
				String msg = data.getData().getString("msg");
				String[] parts = msg.split(";");

				if (parts[0].equals("POST_GAME")) {
					setName(parts[1]);
					setBadge(parts[2]);
					setEnemyName(parts[3]);
					setEnemyColor(parts[4]);
					startGame();
				}
			}
		};

		connection = new GameConnection(updateHandler, 0);
		
		connection.connectToServer(selectedServer.getHost(), selectedServer.getPort());
		
		connection.sendMessage("GET_GAME");
	}
	
	private void setName(String name) {
		this.gameName = name;
		if (badge != null)
			startGame();
	}
	
	private void setBadge(String color) {
		Badge usedBadge = AllBadges.ALL_BADGES.get(color);
		
		Iterator<Entry<String, Badge>> it = AllBadges.ALL_BADGES.entrySet().iterator();
	    while (it.hasNext()) {
	    	Map.Entry<String, Badge> instance = (Map.Entry<String, Badge>)it.next();
	        if (!instance.getValue().equals(usedBadge)) {
	        	this.badge = instance.getKey();
	        	break;
	        }
	    }
	}
	
	private void setEnemyName(String name) {
		enemyName = name;
	}
	
	private void setEnemyColor(String color) {
		enemyColor = color;
	}
	
	private void startGame() {
		Intent gameIntent = new Intent(JoinGameActivity.this, GameActivity.class);
		
		String playerName = ((TextView) findViewById(R.id.playerNameJoin)).getText().toString();

		if (playerName == null || playerName.isEmpty()) {
			Toast.makeText(this, "Type your nick first!", Toast.LENGTH_SHORT).show();
			return;
		}
		
		gameIntent.putExtra("isServer", 0);
		gameIntent.putExtra("port", selectedServer.getPort());
		gameIntent.putExtra("host", selectedServer.getHost());
		gameIntent.putExtra("game_name", gameName);
		gameIntent.putExtra("player_name", playerName);
		gameIntent.putExtra("player_color", badge);
		gameIntent.putExtra("enemy_name", enemyName);
		gameIntent.putExtra("enemy_color", enemyColor);
		
		connection.sendMessage("PLAYER;" + playerName + ";" + badge);
		
		startActivity(gameIntent);
	}
	
	public void refreshButtonClicked(View v) {
		List<NsdServiceInfo> serverList = new ArrayList<NsdServiceInfo>(
				nsdHelper.getDiscoveredServices().values());
		NsdServiceInfo[] servers = serverList.toArray(new NsdServiceInfo[serverList.size()]);
		serversAdapter = new ServerListAdapter(getBaseContext(), servers);
		serversListView.setAdapter(serversAdapter);
	}
}
